package com.mufeng.flutter_wanandroid_ohos

import ExampleHostApi
import FlutterError
import MessageData
import MessageFlutterApi
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.plugins.FlutterPlugin

private class PigeonApiInplementation: ExampleHostApi{
    override fun getHostLanguage(): String {
        return "kotlin"
    }

    override fun add(a: Long, b: Long): Long {
        if (a < 0L || b < 0L){
            throw FlutterError("code", "message", "details")
        }
        return a + b
    }

    override fun sendMessage(message: MessageData, callback: (Result<Boolean>) -> Unit) {
        if (message.code == Code.ONE){
            callback(Result.failure(FlutterError("code", "message", "details")))
            return
        }
        callback(Result.success(true))
    }

}

private class PigeonFlutterApi {

    var flutterApi: MessageFlutterApi? = null

    constructor(binding: FlutterPlugin.FlutterPluginBinding) {
        flutterApi = MessageFlutterApi(binding.getBinaryMessenger())
    }

    fun callFlutterMethod(aString: String, callback: (Result<String>) -> Unit) {
        flutterApi!!.flutterMethod(aString) {
                echo -> callback(Result.success(echo))
        }
    }
}

class MainActivity: FlutterActivity(){
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        val api = PigeonApiInplementation()
        ExampleHostApi.setUp(flutterEngine.getDartExecutor().getBinaryMessenger(), api)
    }
}
